package com.demo.weather.server.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.demo.weather.packet.data.FunctionType;
import com.demo.weather.packet.data.PacketData;
import com.demo.weather.receiver.PacketReceiver;
import com.demo.weather.receiver.ReceiverRouter;

import io.netty.channel.ChannelHandlerContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@AllArgsConstructor(onConstructor_ = {@Autowired})
@Component
public class PacketDataHandler extends AbstractServerHandler<PacketData> {
    
	private ReceiverRouter receiverRouter;
	
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PacketData packetData) throws Exception {
    	if(packetData.getHeader() == null) {
    		log.error("数据包解析失败，断开连接");
    		ctx.close();
    		return;
    	}
    	
    	FunctionType functionType = packetData.getHeader().getFunctionType();

    	PacketReceiver packetReceiver = receiverRouter.route(functionType);
        if (packetReceiver == null) {
            log.error("Do not support functionType: {}", functionType);
            return;
        }
        
        try {
	        // 根据不同的包，交由不同的receiver去处理
        	packetReceiver.handle(packetData);
    	} catch(Throwable t) {
            log.error("Error processing channelRead. packetData:{}", packetData.toString(), t);
    	} finally {
            ctx.flush();
    	}
    }
}